package com.qf.web.servlet;


import com.qf.pojo.CartDto;
import com.qf.pojo.TbAddress;
import com.qf.pojo.TbOrder;
import com.qf.pojo.TbUser;
import com.qf.service.AddressService;
import com.qf.service.OrderService;
import com.qf.service.impl.AddressServiceImpl;
import com.qf.service.impl.OrderServiceImpl;
import com.qf.utils.StringConstans;
import com.qf.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * Create by 周志豪 on 2022/8/18 20:51
 *
 * @authoe 周志豪
 * @veision 1.0
 * //TODO  想好了再去做
 * @since 1.0
 */
public class OrderServlet {

    private OrderService orderService = new OrderServiceImpl();

    private AddressService addressService = new AddressServiceImpl();

    public String preView(HttpServletRequest req, HttpServletResponse resp) {
        TbUser user = (TbUser) req.getSession().getAttribute("user");

        Long userId = user.getId();
        List<TbAddress> addressList = addressService.findAllAddressByUserId(userId);

        req.getSession().setAttribute("addressList", addressList);
        return StringConstans.REDIRECT + "/order.jsp";
    }

    public String create (HttpServletRequest req, HttpServletResponse resp) {

        TbUser user = (TbUser) req.getSession().getAttribute("user");
        Long userId = user.getId();
        CartDto cart = (CartDto) req.getSession().getAttribute("cart");

        if (cart == null || cart.getGoodsList() == null || cart.getGoodsList().size() == 0) {
            return StringConstans.REDIRECT + "/index.jsp";
        }


        String addressId = req.getParameter("aid");
        if (StringUtils.isEmpty(addressId)) {
            return StringConstans.REDIRECT + "/order?method=preView";
        }


        Map result = orderService.createOrder(userId, Long.parseLong(addressId), cart);
        //垃圾回收
        cart.getGoodsList().clear();
        cart.setNums(null);
        req.getSession().removeAttribute("cart");

        req.getSession().setAttribute("order",result);
        return StringConstans.REDIRECT + "/orderSuccess.jsp";
    }

    public String show (HttpServletRequest req, HttpServletResponse resp) {
        TbUser user = (TbUser) req.getSession().getAttribute("user");
        Long userId = user.getId();
        List<TbOrder> orderList = orderService.findByUserId(userId);
        req.getSession().setAttribute("ordersList", orderList);
        return StringConstans.REDIRECT + "/orderList.jsp";
    }
}
